package com.atguigu.security.config;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @author maomeng
 * @create 2021-06-09- 15:16
 */

@Component
public class MyPasswordEncoder implements PasswordEncoder {

    /**
     * 加密方法
     * @param rawPassword 未经加密的明文密码
     * @return
     */
    @Override
    public String encode(CharSequence rawPassword) {
        return md5Encode(rawPassword);
    }

    /**
     *
     * @param rawPassword
     * @param encodedPassword
     * @return
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String encoded = md5Encode(rawPassword);

        boolean equals = Objects.equals(encoded, encodedPassword);

        return encoded.equals(encodedPassword);
    }

    /**
     * 对加密的流程进行单独抽取
     * @param rawPassword
     * @return
     */

    private String md5Encode(CharSequence rawPassword){
        //创建messageDigest对象
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 获取rawPassword的输入的字节数组
            byte[] inputPassword = ((String) rawPassword).getBytes();

            // 执行加密
            byte[] outputPassword = messageDigest.digest(inputPassword);

            // 转换为16进制数对应的字符
            String encoded = new BigInteger(1, outputPassword).toString(16).toUpperCase();

            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
